$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

/**
 *搜索专用区
 参数：searchId:搜索框searchbox 的id
 datagridId:数据表格ID
 searcher:搜索函数名,搜索函数有两个参数，(value,name)，分别对应值和后台名称
 fieldNotToSearch:不搜索字段的title，datagrid的title字段，为数组
 var fieldNotToSearch=['Request Id','Request Detail Id','Requestor Id'];
 SearchCombobox('testRequstSearchBox','testRequestTable',testRequest.searchRequest,fieldNotToSearch);
 **/
function SearchCombobox(searchId, datagridId, searcher, fieldNotToSearch, promptText) {
    if (!promptText) {
        promptText = '';
    }
    var searchboxId = datagridId + 'SearchMenu';
    if ($('#' + searchboxId).length > 0) {
        $('#' + searchboxId).remove();
    }
    if ($('#' + searchboxId).length == 0) {
        $("body").append('<div id="' + searchboxId + '"></div>');
    }
    var searchMenu = $('#' + searchboxId);
    var search = $('#' + searchId);
    var tbObject = $('#' + datagridId);
    var allFields = tbObject.datagrid('getColumnFields', true);
    var allFields2 = tbObject.datagrid('getColumnFields');
    for (var i = 0; i < allFields.length; i++) {
        var fieldToName = tbObject.datagrid('getColumnOption', allFields[i]);
        let title = fieldToName.title.replace(/<[^>]+>/g, "");
        if (fieldNotToSearch.indexOf(fieldToName.field) < 0) {
            searchMenu.append('<div data-options="name:' + "'" + allFields[i] + "'" + ',iconCls:' + "'icon-bullet_white'" + '">' + title + '</div>');
        }
    }
    for (var i = 0; i < allFields2.length; i++) {
        var fieldToName = tbObject.datagrid('getColumnOption', allFields2[i]);
        let title = fieldToName.title.replace(/<[^>]+>/g, "");
        if (fieldNotToSearch.indexOf(fieldToName.field) < 0 && true !== fieldToName.hidden) {
            searchMenu.append('<div data-options="name:' + "'" + allFields2[i] + "'" + ',iconCls:' + "'icon-bullet_white'" + '">' + title + '</div>');
        }
    }

    search.searchbox({
        plain: true,
        prompt: promptText,
        width:250,
        height:25,
        menu: '#' + searchboxId,
        searcher: function (value, name) {
            searcher(value, name);
        }
    });

}

function clearDialogHtml(dialogIds){
    for(var i in dialogIds){
        var ID = $('#'+dialogIds[i]+'.panel-body');
        if(ID.length>0){
            ID.remove();
        }
    }
}

function DialogSearchCombobox(searchId, datagridId, fieldNotToSearch, promptText) {
    if (!promptText) {
        promptText = '';
    }
    var searchboxId = datagridId + 'SearchMenu';
    if ($('#' + searchboxId).length > 0) {
        $('#' + searchboxId).remove();
    }
    if ($('#' + searchboxId).length == 0) {
        $("body").append('<div id="' + searchboxId + '"></div>');
    }
    var searchMenu = $('#' + searchboxId);
    var search = $('#' + searchId);
    var tbObject = $('#' + datagridId);
    var allFields = tbObject.datagrid('getColumnFields', true);
    var allFields2 = tbObject.datagrid('getColumnFields');
    for (var i = 0; i < allFields.length; i++) {
        var fieldToName = tbObject.datagrid('getColumnOption', allFields[i]);
        let title = fieldToName.title.replace(/<[^>]+>/g, "");
        if (fieldNotToSearch.indexOf(title) < 0) {
            searchMenu.append('<div data-options="name:' + "'" + allFields[i] + "'" + ',iconCls:' + "'icon-bullet_white'" + '">' + title + '</div>');
        }
    }
    for (var i = 0; i < allFields2.length; i++) {
        var fieldToName = tbObject.datagrid('getColumnOption', allFields2[i]);
        let title = fieldToName.title.replace(/<[^>]+>/g, "");
        if (fieldNotToSearch.indexOf(title) < 0) {
            searchMenu.append('<div data-options="name:' + "'" + allFields2[i] + "'" + ',iconCls:' + "'icon-bullet_white'" + '">' + title + '</div>');
        }
    }
    return searchboxId;
}

var dialogThreeColumnWidth = 1200;
var dialogTwoColumnWidth = 800;
var dialogDefaultWidth = 600;
var dialogDefaultHeight = 550;
var commonSelectOption = {
    theme_id: {
        data: getThemeOption(),
        textField: 'theme_name',
        valueField: 'id',
        width: 100,
    },
    cate_id: {
        data: getCategoryOption(),
        textField: 'cate_name',
        valueField: 'id',
        width: 100,
    },
    dynasty: {
        data: getPoemDynastyOption(),
        textField: 'text',
        valueField: 'value',
        width: 100,
    },
    poem_level: {
        data: getPoemLevelOption(),
        textField: 'text',
        valueField: 'value',
        width: 100,
    },
    year: {
        data: getYearOption(),
        textField: 'text',
        valueField: 'value',
        width: 80,
    },
    month: {
        data: getMonthOption(),
        textField: 'text',
        valueField: 'value',
        width: 80,
    },
    word_type:{
        data: getWordTypeOption(),
        textField: 'text',
        valueField: 'value',
        width: 80,
    }
};

function loadFilter(response, hasPagination) {
    if(hasPagination){
        var value = {total: response.data.pagination.total, rows: response.data.list};
    }else{
        var value = {rows: response.data};
    }
    return value;
}

function loadOptionFilter(response) {
    var value = {rows: response.data};
    return value;
}

function initComboboxOption(functionName, fieldArr) {
    $.each(fieldArr, function (i, field) {
        if (commonSelectOption.hasOwnProperty(field)) {
            $("#ele_select_" + field + "_in_" + functionName).combobox(commonSelectOption[field]);
        }
    });
}

function getThemeOption() {
    var optionData;
    $.ajax({
        url: 'api/article_theme/option',
        async: false,
        type: 'post',
        data: {},
        success: function (resp) {
            if (1 == resp.code) {
                optionData = resp.data;
            }
        }
    });
    return optionData;
}

function getCategoryOption(themeId) {
    var optionData;
    $.ajax({
        url: 'api/article_category/option',
        async: false,
        type: 'post',
        data: {theme_id: themeId},
        success: function (resp) {
            if (1 == resp.code) {
                optionData = resp.data;
            }
        }
    });
    console.log(optionData);
    return optionData;
}

function getWordTypeOption() {
    var optionData;
    $.ajax({
        url: '/api/Option/getWordTypeOption',
        async: false,
        type: 'post',
        data: {},
        success: function (resp) {
            if (1 == resp.code) {
                optionData = resp.data;
            }
        }
    });
    return optionData;
}

function getBottomMenuOption()
{
    var optionData;
    $.ajax({
        url: '/api/SelectOption/getBottomMenuList',
        async: false,
        type: 'post',
        data: {},
        dataType:'json',
        success: function (resp) {
            if (1 == resp.code) {
                optionData = resp.data;
            }
        }
    });
    console.log(optionData);
    return optionData;
}

function getDictionarySubOption(code)
{
    var optionData;
    $.ajax({
        url: '/api/DictionarySub/getDictionarySubOption',
        async: false,
        type: 'post',
        data: {dictionary_code: code},
        dataType:'json',
        success: function (resp) {
            if (1 == resp.code) {
                optionData = resp.data;
            }
        }
    });
    console.log(optionData);
    return optionData;
}

function initFormElement(boxId, formFieldConfig) {
    var boxObject = $("#" + boxId);
    $.each(formFieldConfig, function (index, item) {
        switch (item.type) {
            case 'text':
                boxObject.find("input[name=" + index + "]").textbox(item.config);
                break;
            case 'select':
                boxObject.find("input[name=" + index + "]").combobox(item.config);
                break;
            case 'number':
                boxObject.find("input[name=" + index + "]").numberbox(item.config);
                break;
            case 'tag':
                boxObject.find("input[name=" + index + "]").tagbox(item.config);
                break;
        }
    });
}

function getDatagridCheckedRowId(tableObject, opText){
    var checkList = tableObject.datagrid('getChecked');
    if(checkList.length < 1){
        layer.msg('请选择要'+ opText +'的数据');
        return false;
    }
    var arrCheckId = [];
    $.each(checkList, function(index, item){
        arrCheckId.push(item.id);
    });
    return arrCheckId;
}


function getDatagridCheckedRowData(tableObject, opText){
    var checkList = tableObject.datagrid('getChecked');
    if(checkList.length < 1){
        layer.msg('请选择要'+ opText +'的数据');
        return false;
    }
    return checkList;
}

function formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
}

function formatMonthDate(date){
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    return `${year}-${month}`;
}

function getFilterData(subjectKeyword, searchFieldInput, searchFieldSingleSelect, searchFieldManySelect)
{
    var filterConfig = {};
    $.each(searchFieldInput, function (index, fieldName) {
        var id = "#ele_input_" + fieldName + "_in_" + subjectKeyword;
        filterConfig[fieldName] = $(id).textbox('getValue');
    });

    $.each(searchFieldSingleSelect, function (index, fieldName) {
        var id = "#ele_select_" + fieldName + "_in_" + subjectKeyword;
        filterConfig[fieldName] = $(id).combobox('getValue');
    });

    $.each(searchFieldManySelect, function (index, fieldName) {
        var id = "#ele_select_" + fieldName + "_in_" + subjectKeyword;
        //支持多选
        filterConfig[fieldName] = $(id).combobox('getValues');
    });
    return filterConfig;
}

function clearFilterData(subjectKeyword, searchFieldInput, searchFieldSingleSelect, searchFieldManySelect)
{
    var filterConfig = {};
    $.each(searchFieldInput, function (index, fieldName) {
        var id = "#ele_input_" + fieldName + "_in_" + subjectKeyword;
        $(id).textbox('setValue', '');
        filterConfig[fieldName] = '';
    });

    $.each(searchFieldSingleSelect, function (index, fieldName) {
        var id = "#ele_select_" + fieldName + "_in_" + subjectKeyword;
        $(id).combobox('setValue', '');
        filterConfig[fieldName] = '';
    });

    $.each(searchFieldManySelect, function (index, fieldName) {
        var id = "#ele_select_" + fieldName + "_in_" + subjectKeyword;
        //支持多选
        $(id).combobox('setValue', '');
        filterConfig[fieldName] = '';
    });
    return filterConfig;
}

function initSelectField(subjectKeyword, arrSelectField1, arrSelectField2, searchOption){
    $.each(arrSelectField1, function(i, field){
        if(searchOption.hasOwnProperty(field)){
            $("#ele_select_" + field + "_in_" + subjectKeyword).combobox(searchOption[field]);
        }
    });

    $.each(arrSelectField2, function(i, field){
        if(searchOption.hasOwnProperty(field)){
            $("#ele_select_" + field + "_in_" + subjectKeyword).combobox(searchOption[field]);
        }
    });
}

function renderTagBox(boxId, dataList, showField){
    var boxObject = $("#" + boxId);
    var html = '';
    $.each(dataList, function(index, item){
        html += '<div data-id="' + item.id + '" class="tag-item">' + item[showField]+ '<i class="fa fa-trash"></i></div>'
    });
    boxObject.html(html);
}

//渲染前端展示列表的box
function renderFrontShowListBox(boxId, dataList, showField){
    var boxObject = $("#" + boxId);
    var html = '';
    $.each(dataList, function(index, item){
        html += '<div data-id="' + item.id + '" class="tag-item">' + item[showField]+ '</div>'
    });
    boxObject.html(html);
}




